package com.example.canteen.dao.impl;

import com.example.canteen.dao.FoodDao;
import com.example.canteen.domain.Food;
import com.example.canteen.util.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class FoodDaoImpl implements FoodDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    @Override
    public Food findById(int id) {
        Food food = null;
        String sql = "SELECT id,name FROM food WHERE id=?";
        try {
            food =template.queryForObject(sql,new BeanPropertyRowMapper<Food>(Food.class),id);
        }catch (Exception e){

        }
        return food;
    }

    @Override
    public List<Food> findAll() {
        String sql = "SELECT id,name FROM food";
        return template.query(sql, new BeanPropertyRowMapper<Food>(Food.class));
    }


    @Override
    public int delete(int id) {
        String sql = "DELETE FROM food WHERE id=?";
        return template.update(sql,id);
    }

    @Override
    public void save(Food food) {
        String sql = "insert into food(id,name) value(?,?)";
        template.update(sql,food.getId(),
                food.getName());

    }

    @Override
    public int update(Food food) {
        String sql = "UPDATE food SET name=? WHERE id=?";
        return template.update(sql,food.getName(),food.getId());

    }
}
